package com.qf.mybatisDynamicSqlDemo.until;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * @author 刘欣
 * @createTime 2022/12/22 20:31
 * @description
 */
public class MybatisUntil<T> {
    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession() {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
            return sqlSession;
        }
        sqlSession = sqlSessionFactory.openSession();
        threadLocal.set(sqlSession);
        return sqlSession;
    }

    public static void commit() {
        SqlSession sqlSession = getSqlSession();
        sqlSession.commit();
        closeSqlSession();
    }

    public static void closeSqlSession() {
        SqlSession sqlSession = getSqlSession();
        threadLocal.remove();
        sqlSession.close();
    }

    public static <T> T getMapper(Class<T> clazz) {
        SqlSession sqlSession = getSqlSession();
        T mapper = sqlSession.getMapper(clazz);
        return mapper;
    }
}
